﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InfoService.Enums;
using InfoService.Utils;
using MediaPortal.GUI.Library;
using Action = MediaPortal.GUI.Library.Action;

namespace InfoService.RecentlyAdded
{
    public static class RecentlyAddedUpdater
    {
        private static readonly Logger logger = Logger.GetInstance();
        private static bool FirstRefresh = true;
        private static DateTime LastRefresh = DateTime.MinValue;

        public static void SetupUpdater()
        {
            UpdateTimer.OnTimeForUpdateProperties += new UpdateTimer.UpdatePropertiesHandler(UpdateTimer_UpdateProperties);
            GUIWindowManager.Receivers += new SendMessageHandler(GUIWindowManager_Receivers);
            GUIWindowManager.OnNewAction += new OnActionHandler(GUIWindowManager_OnNewAction);
        }

        static void GUIWindowManager_OnNewAction(MediaPortal.GUI.Library.Action action)
        {
            if(action.wID == Action.ActionType.ACTION_SELECT_ITEM && GUIWindowManager.ActiveWindow == 35) // 35 = Basichome
            {
                logger.WriteLog("Getting Basichome GUIWindow...", LogLevel.Debug, InfoServiceModul.RecentlyAdded);
                GUIWindow fWindow = GUIWindowManager.GetWindow(GUIWindowManager.ActiveWindow);
                if (fWindow != null)
                {
                    logger.WriteLog("Basichome Window found...", LogLevel.Debug, InfoServiceModul.RecentlyAdded);
                    int id = fWindow.GetFocusControlId();
                    if (id == 50000) //This should be the ID of the first Recently Added control
                    {
                        logger.WriteLog("Recently Added Item 1 selected", LogLevel.Info, InfoServiceModul.RecentlyAdded);
                        //TODO: Play video file from #infoservice.recentlyadded1.filename
                    }
                    else if (id == 50001) //This should be the ID of the second Recently Added control
                    {
                        logger.WriteLog("Recently Added Item 2 selected", LogLevel.Info, InfoServiceModul.RecentlyAdded);
                        //TODO: Play video file from #infoservice.recentlyadded2.filename
                    }
                    else if (id == 50002) //This should be the ID of the third Recently Added control
                    {
                        logger.WriteLog("Recently Added Item 3 selected", LogLevel.Info, InfoServiceModul.RecentlyAdded);
                        //TODO: Play video file from #infoservice.recentlyadded3.filename
                    }
                }
            }
            
        }

        private static void GUIWindowManager_Receivers(GUIMessage message)
        {
            if (message.Message == GUIMessage.MessageType.GUI_MSG_USER)
            {
                if (message.TargetWindowId == InfoServiceCore.GUIInfoServiceId)
                {
                    logger.WriteLog("Received a recently added message", LogLevel.Debug, InfoServiceModul.RecentlyAdded);
                    if (message.Object != null)
                    {
                        logger.WriteLog("Setting received recently added message to properties", LogLevel.Info, InfoServiceModul.RecentlyAdded);
                        string[] details = (string[])message.Object;
                        string type = details[0].ToLower();

                        string Title1 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Title, type, 1));
                        string Title2 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Title, type, 2));
                        string Title3 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Title, type, 3));
                        string Season1 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Season, type, 1));
                        string Season2 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Season, type, 2));
                        string Season3 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Season, type, 3));
                        string Episodenumber1 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodenumber, type, 1));
                        string Episodenumber2 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodenumber, type, 2));
                        string Episodenumber3 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodenumber, type, 3));
                        string Episodetitle1 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodetitle, type, 1));
                        string Episodetitle2 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodetitle, type, 2));
                        string Episodetitle3 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodetitle, type, 3));
                        string Thumb1 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Thumb, type, 1));
                        string Thumb2 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Thumb, type, 2));
                        string Thumb3 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Thumb, type, 3));
                        string Fanart1 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Fanart, type, 1));
                        string Fanart2 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Fanart, type, 2));
                        string Fanart3 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Fanart, type, 3));
                        string DateAdded1 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.DateAdded, type, 1));
                        string DateAdded2 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.DateAdded, type, 2));
                        string DateAdded3 = GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.DateAdded, type, 3));
                        //DateTime DateAdded1 = DateTime.Parse(DateAdded1str);
                        //DateTime DateAdded2 = DateTime.Parse(GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.DateAdded, type, 2)));
                        //DateTime DateAdded3 = DateTime.Parse(GUIPropertyManager.GetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.DateAdded, type, 3)));

                        string[] seriesInfo = details[1].Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);

                        if (type == "series" && details.Length == 4 && seriesInfo.Length == 4)
                        {
                            string TitleNew = seriesInfo[0];
                            string SeasonNew = seriesInfo[1];
                            string EpisodenumberNew = seriesInfo[2];
                            string EpisodetitleNew = seriesInfo[3];
                            string ThumbNew = details[2];
                            string FanartNew = details[3];

                            logger.WriteLog(string.Format("Received recently added message - {0}:{1}/{2}/{3}/{4}:{5}:{6}:{7}", RecentlyAddedType.Series, TitleNew, SeasonNew, EpisodenumberNew, EpisodetitleNew, ThumbNew, FanartNew, DateTime.Now), LogLevel.Debug, InfoServiceModul.RecentlyAdded);

                            if (Title1 == TitleNew && Season1 == SeasonNew && Episodenumber1 == EpisodenumberNew && Episodetitle1 == EpisodetitleNew)
                                return;

                            if (Title2 == TitleNew && Season2 == SeasonNew && Episodenumber2 == EpisodenumberNew && Episodetitle2 == EpisodetitleNew)
                                return;

                            if (Title3 == TitleNew && Season3 == SeasonNew && Episodenumber3 == EpisodenumberNew && Episodetitle3 == EpisodetitleNew)
                                return;

                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Title, type, 2), Title1);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Season, type, 2), Season1);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodenumber, type, 2), Episodenumber1);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodetitle, type, 2), Episodetitle1);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Thumb, type, 2), Thumb1);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Fanart, type, 2), Fanart1);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.DateAdded, type, 2), DateAdded1);
                            
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Title, type, 3), Title2);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Season, type, 3), Season2);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodenumber, type, 3), Episodenumber2);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodetitle, type, 3), Episodetitle2);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Thumb, type, 3), Thumb2);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Fanart, type, 3), Fanart2);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.DateAdded, type, 3), DateAdded2);

                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Title, type, 1), TitleNew);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Season, type, 1), SeasonNew);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodenumber, type, 1), EpisodenumberNew);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Episodetitle, type, 1), EpisodetitleNew);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Thumb, type, 1), ThumbNew);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Fanart, type, 1), FanartNew);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.DateAdded, type, 1), DateTime.Now.ToShortDateString());
                        }
                        else if (type == "movie" && details.Length == 4)
                        {
                            string TitleNew = details[1];
                            string ThumbNew = details[2];
                            string FanartNew = details[3];

                            logger.WriteLog(string.Format("Received recently added message - {0}:{1}:{2}:{3}:{4}", RecentlyAddedType.Movie, TitleNew, ThumbNew, FanartNew, DateTime.Now), LogLevel.Debug, InfoServiceModul.RecentlyAdded);

                            if (Title1 == TitleNew || Title2 == TitleNew || Title3 == TitleNew)
                                return;

                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Title, type, 1), details[1]);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Thumb, type, 1), details[2]);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Fanart, type, 1), details[3]);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.DateAdded, type, 1), DateTime.Now.ToShortDateString());
                            
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Title, type, 2), Title1);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Thumb, type, 2), Thumb1);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Fanart, type, 2), Fanart1);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.DateAdded, type, 2), DateAdded1);
                            
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Title, type, 3), Title2);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Thumb, type, 3), Thumb2);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.Fanart, type, 3), Fanart2);
                            PropertyUtils.SetProperty(string.Format(PropertyUtils.Properties.RecentlyAdded.DateAdded, type, 3), DateAdded2);
                        }
                    }
                    else
                    {
                        logger.WriteLog("The received recently added message was empty. Skip that message", LogLevel.Warning, InfoServiceModul.RecentlyAdded);
                    }
                }
            }
        }

        static void UpdateTimer_UpdateProperties()
        {
            if (FirstRefresh)
            {
                RecentlyAddedUtils.LoadLastRecentlyAddedItems();
                LastRefresh = DateTime.Now;
                FirstRefresh = false;
            }

            TimeSpan spanWeather = DateTime.Now - LastRefresh;

            if (((int)spanWeather.TotalMinutes) >= 120) //every 2 hours
            {
                logger.WriteLog("Updating recently added properties...", LogLevel.Debug, InfoServiceModul.RecentlyAdded);
                RecentlyAddedUtils.ReloadRecentlyAddedProperties();
                LastRefresh = DateTime.Now;
            }
        }
    }
}
